package wiki.tools.vidition.droid.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtil {
	public static String saveFile(String fileName, String content) {
		String message = "";
		File file = new File(fileName);
		if (file.exists()) {
			message = "The bookmark is exists!";
		} else {
			FileWriter writer = null;
			try {
				writer = new FileWriter(file);
				writer.write(content);
				writer.flush();
				message = "Save success!";
			} catch (IOException e) {
				message = "Save error!";
			} finally {
				if (null != writer) {
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					writer = null;
				}
			}
		}
		return message;
	}

	public static String saveNote(String fileName, String content) {
		String message = "";
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}
		FileWriter writer = null;
		try {
			writer = new FileWriter(file);
			writer.write(content);
			writer.flush();
			message = "Save success!";
		} catch (IOException e) {
			message = "Save error!";
		} finally {
			if (null != writer) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				writer = null;
			}
		}
		return message;
	}

	public static String readFile(File file) {
		FileReader reader = null;
		StringBuilder builder = new StringBuilder();
		try {
			char[] buf = new char[2048];
			reader = new FileReader(file);
			int len = -1;
			while (-1 != (len = reader.read(buf))) {
				builder.append(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != reader) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				reader = null;
			}
		}

		return builder.toString();
	}

}